package team.southcat.wsyygh.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import team.southcat.wsyygh.common.mapper.AreaMapper;
import team.southcat.wsyygh.common.service.AreaService;
import team.southcat.wsyygh.model.pojo.common.Area;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author QiuSiYi
 * @since 2023-04-20
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    //查询所有省份信息
    @Override
    @Cacheable("area_cache")
    public List<Area> getChildByParentId(int parentId) {
        LambdaQueryWrapper<Area> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Area::getParentId, parentId);

        List<Area> areas = baseMapper.selectList(queryWrapper);
        //向list集合每个省份信息中设置hasChildren
        for(Area area:areas){
            int areaId = area.getId();
            boolean isChild = this.isChildren(areaId);
            area.setHasChildren(isChild);
        }
        return areas;
    }

    @Override
    public List<Area> getAllProvince() {
        LambdaQueryWrapper<Area> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Area::getParentId, 0);
        List<Area> areas = baseMapper.selectList(queryWrapper);
        return areas;
    }

    //根据代码获取子数据
    @Override
    public List<Area> findByAreaCode(String areaCode) {
        if ("Province".equals(areaCode)){
            return this.getChildByParentId(0);
        }
        if ("City".equals(areaCode)){
            return this.getAllCity();
        }
        if ("District".equals(areaCode)){
            return this.getALlDistrict();
        }
        return null;
    }

    private List<Area> getALlDistrict() {
        List<Area> allCity = this.getAllCity();
        List<Area> res = new ArrayList<>();
        for (Area area : allCity) {
            List<Area> child = this.getChildByParentId(area.getId());
            res.addAll(child);
        }
        return res;
    }

    private List<Area> getAllCity() {
        List<Area> provinces = this.getChildByParentId(0);
        List<Area> res = new ArrayList<>();
        for (Area province : provinces) {
            List<Area> citys = this.getChildByParentId(province.getId());
            res.addAll(citys);
        }
        return res;
    }

    //判断id下面是否有子节点
    private  boolean isChildren(int id){
        LambdaQueryWrapper<Area> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Area::getParentId, id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count>0;
    }
}
